<template>
  <div class="project-change">
    <div class="project-change-title">ICT项目变更发起</div>
    <div class="flex">
      <div style="flex: 1">
        <!-- 项目基本信息 -->
        <div class="desc-item">
          <div class="form-item">项目基本信息</div>
          <el-descriptions class="mb-16" :column="2" :border="true">
            <el-descriptions-item
              v-for="(descItem, index) in projectBasicDescs"
              :key="index"
              :label="descItem.label"
              label-class-name="desc-label"
              :class-name="'desc-content-2'"
            >
              <span>
                {{ descItem.content }}
              </span>
            </el-descriptions-item>
          </el-descriptions>
        </div>
        <!-- 变更字段 -->
        <div class="desc-item">
          <div class="form-item">项目变更信息</div>
          <!-- 使用v-for循环渲染所有环节的变更表格 -->
          <StageChangeTable
            v-for="stage in filteredStageConfigs"
            :key="stage.key"
            :title="stage.title"
            :sourceData="projectChaneKeys[stage.key]"
            :ref="(el) => { if(el) stageRefs[stage.key] = el }"
          />
          <div v-if="showAutonomousAbility">
            <div class="table-title" > 自主能力信息 </div>
            <div class="autonomous-comparison">
              <!-- 对比容器 -->
              <div class="comparison-container">
                <!-- 旧值 -->
                <div class="version-box old-version">
                  <div class="version-label">
                    <el-tag type="info">原值</el-tag>
                  </div>
                  <AutonomousAbilitySelector
                    :descriptions="autonomousAbilityDesc"
                    :readOnly="true"
                    class="data-panel"
                  />
                </div>
                
                <!-- 新值 -->
                <div class="version-box new-version">
                  <div class="version-label">
                    <el-tag type="success">新值</el-tag>
                  </div>
                  <AutonomousAbilitySelector
                    :descriptions="autonomousAbilityDesc"
                    :readOnly="false"
                    class="data-panel"
                    ref="autonomousSelector"
                  />
                </div>
              </div>
            </div>
          </div>

          <!-- 审批人选择 -->
          <div>
            <div class="table-title">审批人选择</div>
            <el-form ref="formRef" :model="approvalUsersFormData">
              <el-descriptions class="mb-16" :column="1" :border="true">
                <el-descriptions-item
                  :label="'建设单位部门经理'"
                  label-class-name="desc-label"
                  :class-name="'desc-content-1'"
                >
                  <el-form-item 
                    prop="construction_dept_manager" 
                    class="user-select-form-item"
                  >
                    <div class="flex">
                      <el-input 
                        v-model="approvalUsersFormData.construction_dept_manager" 
                        placeholder="请选择建设单位部门经理"  
                        :readonly="true"
                      />
                      <el-button 
                        type="primary" 
                        class="ml-8" 
                        @click="openUserSelect('construction_dept_manager')"
                      >选择用户</el-button>
                    </div>
                  </el-form-item>
                </el-descriptions-item>
                <el-descriptions-item
                  :label="'省端项目主管'"
                  label-class-name="desc-label"
                  :class-name="'desc-content-1'"
                  >
                  <el-form-item 
                    prop="project_supervisor" 
                    class="user-select-form-item"
                  >
                    <div class="flex">
                      <el-input 
                        v-model="approvalUsersFormData.project_supervisor" 
                        placeholder="请选择省端项目主管"
                        :readonly="true"
                      />
                      <el-button 
                        type="primary" 
                        class="ml-8" 
                        @click="openUserSelect('project_supervisor')"
                      >选择用户</el-button>
                    </div>
                  </el-form-item>
                </el-descriptions-item>
              </el-descriptions>
            </el-form>
            <!-- 用户选择模态框 -->
            <UserSelectDialog ref="userSelectDialog" :userSelectDialogProps="userSelectDialogProps" @updateSelectedUser="handleSelectedUser" />
          </div>
          
          <!-- 变更原因 -->
          <div class="change-reason">
            <div class="table-title">变更原因</div>
            <el-input
              v-model="change_reason"
              type="textarea"
              :rows="3"
              placeholder="请输入变更原因"
            />
          </div>
          
          <!-- 提交按钮 -->
          <div class="submit-btn">
            <el-button type="primary" @click="projectManagerSubmit">提交变更</el-button>
          </div>
        </div>
      </div>
      <!-- 审批流程 -->
      <div class="timeline">
        <el-timeline style="max-width: 600px; padding-left:10px">
          <el-timeline-item
            v-for="(process, index) in processChangeProcess"
            :key="index"
            :color="process.color"
            placement="top"
          >
            <slot name="timestamp">
              <div class="timeline-title">
                {{ process.name }}
                <el-tag color="#ecf5ff" :style="{ color: process.color }">{{
                  process.status
                }}</el-tag>
              </div>
            </slot>
            <el-card>
              <p>处理人：{{ process.assigneeUsername }}</p>
            </el-card>
          </el-timeline-item>
        </el-timeline>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import * as KmsApi from '@/api/project/kms'
import * as BpmApi from '@/api/project/bpm'
import * as ICTApi from '@/api/project/ict'
import {staticData} from '@/views/project/mixins/staticDataMixin'
import { projectChangeDescriptionFileds } from '@/views/project/projectChange/mixins/projectChangeKeysMixin'
import StageChangeTable from '@/views/project/projectChange/components/StageChangeTable.vue'
import { useTagsViewStore } from '@/store/modules/tagsView'
import { useRouter, useRoute } from 'vue-router'
import { getUserProfile } from '@/api/system/user/profile'
import AutonomousAbilitySelector from '@/views/project/projectDetails/components/AutonomousAbilitySelector.vue';
import { projectGradingDescriptionFileds } from '@/views/project/projectDetails/mixins/projectGradingDetailsMixin'
import UserSelectDialog from '@/views/project/projectDetails/components/UserSelectDialog.vue'

// emit事件合集
const emit = defineEmits(['getApprovalProcess', 'getProjectInfo']);

onBeforeMount(async () => {
  await getProjectStageInfo()
  await getApprovalProcess()
  await getProjectInfo()
  await getUser()
})
  
// data
// 路由
const tagsViewStore = useTagsViewStore()
const router = useRouter()
const route = useRoute()

// 静态变量
const { stageList } = staticData()
const { formatAutonomousType } = projectGradingDescriptionFileds({})

// 流程列表
let processList = ref([])
// 项目信息
let projectInfo = reactive({})

// 用户选择模态框对象
const userSelectDialog = ref()
// 审批人表单信息
const approvalUsersFormData = ref({
  construction_dept_manager: '',
  construction_dept_manager_id: '',
  project_supervisor: '',
  project_supervisor_id: ''
})

const currentFieldName = ref('') // 存储当前选择的 fieldName
const userSelectDialogProps = computed(() => {
  switch (currentFieldName.value) {
    case 'construction_dept_manager':
      return {
        role: 'constructionDepartmentManager',
        execute_region: projectInfo.execute_region
      }
    case 'project_supervisor':
      return {
        role: 'projectSupervisor',
        execute_region: projectInfo.execute_region
      }
    default:
      return { role: '', execute_region: '' } // 默认情况
  }
})
const projectCode = route.query.project_code
const currentProcessInstanceId = ref()
const projectStageInfo = ref([])
const currentProcessStageName = ref()
const currentIndex = ref(0)
const showAutonomousAbility = ref(false)

// 变更相关数据
const change_reason = ref('')
const stageRefs = reactive({})
const allChangeList = ref([])
const autonomousSelector = ref(null)

const projectChaneKeys = reactive({
  projectTransferKeysDesc: [],
  projectGradingKeysDesc: [],
  startupReportingKeysDesc: [],
  testRunKeysDesc: [],
  projectDeliveryKeysDesc: []
})

const projectBasicDescs = computed(() => [
    {
      label: '项目名称',
      content: projectInfo.project_name
    },
    {
      label: '项目管理单位',
      content: projectInfo.project_management_department
    },
    {
      label: '项目编号',
      content: projectInfo.project_number
    },
    {
      label: '项目核算化编码',
      content: projectInfo.project_code
    },
    {
      label: '建设单位',
      content: projectInfo.region
    },
    {
      label: '省端项目主管',
      content: projectInfo.project_supervisor
    },
  ])

const processChangeProcess = computed(() => [
  { 
    status: '当前环节',
    color: '#3f9eff',
    name: '交付经理发起变更',
    assigneeUsername: projectInfo.construction_project_manager
  },
  { 
    status: '待审批环节',
    color: '#909399',
    name: '建设单位部门经理审批',
    assigneeUsername: approvalUsersFormData.construction_dept_manager
  },
  { 
    status: '待审批环节',
    color: '#909399',
    name: '省端主管审批',
    assigneeUsername: approvalUsersFormData.project_supervisor
  }
])

// 环节配置
import { computed } from 'vue'

// const stageConfigs = computed(() => {
//   if (projectInfo.construction_mode === '纯运维') {
//     return [
//       { 
//         key: 'projectTransferKeysDesc',
//         title: '项目移交'
//       },
//       { 
//         key: 'projectDeliveryKeysDesc',
//         title: '项目交付'
//       }
//     ]
//   } else {
//     return [
//       { 
//         key: 'projectTransferKeysDesc',
//         title: '项目移交'
//       },
//       { 
//         key: 'projectGradingKeysDesc',
//         title: '项目定级'
//       },
//       { 
//         key: 'startupReportingKeysDesc',
//         title: '项目开工'
//       },
//       { 
//         key: 'testRunKeysDesc',
//         title: '试运行'
//       },
//       { 
//         key: 'projectDeliveryKeysDesc',
//         title: '项目交付'
//       }
//     ]
//   }
// })
const stageConfigs = [
      { 
        key: 'projectTransferKeysDesc',
        title: '项目移交'
      },
      { 
        key: 'projectGradingKeysDesc',
        title: '项目定级'
      },
      { 
        key: 'startupReportingKeysDesc',
        title: '项目开工'
      },
      { 
        key: 'testRunKeysDesc',
        title: '试运行'
      },
      { 
        key: 'projectDeliveryKeysDesc',
        title: '项目交付'
      }
    ]


const autonomousAbilityDesc= reactive({
    autonomous_type: '',
    autonomous_type_level: '',
    autonomous_group: '',
    autonomous_name: '',
  })

const originAutonomousAbilityDesc= reactive({
  autonomous_type: '',
  autonomous_type_level: '',
  autonomous_group: '',
  autonomous_name: '',
})

// 获取项目基本信息
const getProjectInfo = async () => {
  const params = {
    project_code: projectCode
  }
  try {
    KmsApi.getProjectInfo(params).then((res) => {
      Object.assign(projectInfo, res)

      if(projectInfo.finished) {
        currentProcessStageName.value = '已结束'
      }

      // 获取项目定级阶段的自主能力信息
      autonomousAbilityDesc.autonomous_type = formatAutonomousType(projectInfo.autonomous_type);
      autonomousAbilityDesc.autonomous_type_level = projectInfo.autonomous_type_level;
      autonomousAbilityDesc.autonomous_group = projectInfo.autonomous_group || '';
      autonomousAbilityDesc.autonomous_name = projectInfo.autonomous_name || '';

      originAutonomousAbilityDesc.autonomous_type = projectInfo.autonomous_type;
      originAutonomousAbilityDesc.autonomous_type_level = projectInfo.autonomous_type_level;
      originAutonomousAbilityDesc.autonomous_group = projectInfo.autonomous_group || '';
      originAutonomousAbilityDesc.autonomous_name = projectInfo.autonomous_name || '';
      // 获取项目移交阶段交底人审批意见
      const item = processList.value.find(item => item.name === "项目交底人审批");
      const accepterReason = item ? item.reason : "";
      projectInfo.accepter_reason = accepterReason
      
      KmsApi.getProjectDocInfo(params).then((docRes) => {
        projectInfo.files = docRes || []
        KmsApi.getTeamMembersInfo(params).then((membersRes) => {
          projectInfo.members = membersRes || []
          KmsApi.getExecuteProgressInfo(params).then((progressRes) => {
            projectInfo.progress = progressRes || []
            KmsApi.getReviewInfo(params).then((reviewRes) => {
              projectInfo.reviewInfo = reviewRes || []
              Object.assign(projectChaneKeys, reactive(projectChangeDescriptionFileds(projectInfo)))
            })
          })
        })      
      })

    })
  } catch (error) {
    console.error('项目基本信息获取错误:', error)
  }
}

// 获取审批流程信息
const getApprovalProcess = async (processInstanceId = currentProcessInstanceId.value) => {
  const params = {
    processInstanceId: processInstanceId
  }
  await BpmApi.getApprovalProcessList(params).then((res) => {
    processList.value = res
  })
}

const getProjectStageInfo = async () => {
  const params = {
    project_code_list: [projectCode]
  }
  
  await BpmApi.getProjectStage(params).then(res => {
    projectStageInfo.value = res[projectCode as string]
    currentProcessStageName.value = projectStageInfo.value[0].name
    currentProcessInstanceId.value = projectStageInfo.value[0].id
    currentIndex.value = stageList.indexOf(currentProcessStageName.value);
    if (currentIndex.value > 1) {
      showAutonomousAbility.value = true
    }
  })
}

const filteredStageConfigs = computed(() => {
  return stageConfigs.filter(stage => {
    const stageName = stage.title; // 获取stageConfigs中的环节名称
    const stageIndex = stageList.indexOf(stageName);
    return stageIndex !== -1 && stageIndex < currentIndex.value; // 确保在stageList中存在且在当前环节之前
  });
});

const buildAutonomousChangeList = (autonomousData, originAutonomousAbilityDesc) =>{
  // 字段配置映射表（字段名、显示名称、类型等）
  const fieldConfigs = {
    autonomous_type: {
      field_name: '项目自主类型',
    },
    autonomous_type_level: {
      field_name: '项目自主等级',
    },
    autonomous_group: {
      field_name: '自主能力分类',
    },
    autonomous_name: {
      field_name: '自主能力名称',
    }
  };

  const changeList = [];

  // 遍历所有需要比对的字段
  Object.keys(fieldConfigs).forEach(field => {
    const oldValue = originAutonomousAbilityDesc[field] || '';
    const newValue = autonomousData[field] || '';
    
    const config = fieldConfigs[field];
    
    changeList.push({
      field_name: config.field_name,
      old_value: oldValue,
      new_value: newValue,
      type: config.type,
      filed: field,
      stage: '项目定级'
    });
  });

  return changeList;
}

// 表单验证
const validateForm = () => {
  // 获取所有环节的变更数据
  allChangeList.value = Object.values(stageRefs).flatMap(ref => ref.changeList)
  if (autonomousSelector?.value?.validateForm) {
    autonomousSelector.value.validateForm();
    const autonomousData = autonomousSelector.value?.getFormData()
    allChangeList.value.push(...buildAutonomousChangeList(autonomousData, originAutonomousAbilityDesc))
  }

  
  // 检查是否有任何字段被更改
  const hasChanges = allChangeList.value.some(item => item.new_value !== '' && item.new_value !== item.old_value)
  
  if (!hasChanges) {
    ElMessage.error('请至少更改一个字段')
    return false
  }
  
  if (!change_reason.value) {
    ElMessage.error('请输入变更原因')
    return false
  }
  
  // 只验证已填写的字段
  for (const item of allChangeList.value) {
    if (!item.new_value) continue
    
    if (item.validator === 'number' && isNaN(Number(item.new_value))) {
      ElMessage.error(`${item.field_name}必须是数字`)
      return false
    }
  }

  if (approvalUsersFormData.value.construction_dept_manager_id === '') {
    ElMessage.error('请选择建设单位部门经理')
    return false
  }

  if (approvalUsersFormData.value.project_supervisor_id === '') {
    ElMessage.error('请选择省端项目主管')
    return false
  }

  return true
}

//获取用户信息
const userId = ref(undefined)
const getUser = async () => {
  await getUserProfile().then((res) => {
    userId.value = res.id
  })
}

// 打开选择用户模态框
const openUserSelect = (fieldName) => {
  userSelectDialog.value.currentFieldName = fieldName;
  currentFieldName.value = fieldName
  userSelectDialog.value.userSelectVisible = true
}

// 选中人员事件
const handleSelectedUser = ({ userList, fieldName }) => {
  if (fieldName === 'construction_dept_manager') {
    approvalUsersFormData.value.construction_dept_manager = userList[0].nickname
    approvalUsersFormData.value.construction_dept_manager_id = userList[0].id
  } else if (fieldName === 'project_supervisor') {
    approvalUsersFormData.value.project_supervisor = userList[0].nickname
    approvalUsersFormData.value.project_supervisor_id = userList[0].id
  }
}

// 提交变更
const projectManagerSubmit = async () => {
  if (autonomousSelector?.value?.validateForm) {
    autonomousSelector.value.validateForm();
  }

  if (!validateForm()) return
  // 获取所有有更改的字段
  const changedFields = allChangeList.value
    .filter(item => item.new_value !== '')
    .map(item => ({
      field_name: item.filed,
      old_value: item.old_value,
      new_value: item.new_value,
      // stage: item.stage
    }))
  const params = {
    project_code: projectCode,
    initiator_user_id: userId.value,
    construction_dept_manager_id: approvalUsersFormData.value.construction_dept_manager_id,
    project_supervisor_id: approvalUsersFormData.value.project_supervisor_id,
    change_reason: change_reason.value,
    change_list: changedFields,
    timestamp: Date.now()
  }
  
  try {
    // 表单验证通过，执行提交逻辑
    ElMessageBox.confirm(`是否确认发起项目变更流程单？`, '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {

      await ICTApi.createProjectChange(params).then(() => {
        emit('getProjectInfo')
      })

      ElMessage({
        type: 'success',
        message: '项目变更发起成功'
      })

      tagsViewStore.delView(route)
      router.go(-1)
    })
  } catch (error) {
    console.error('变更提交失败:', error)
    ElMessage.error('变更提交失败')
  }
}
</script>

<style lang="scss" scoped>
@import url('@/views/project/projectDetails/styles/transfer.css');

.user-select-form-item {
  width: 100%;
  
  :deep(.el-form-item__content) {
    width: 100%;
    
    .flex {
      width: 100%;
      display: flex;
      
      .el-input {
        flex: 1;
      }
    }
  }
}

.project-change {
  width: 100%;

  &-title {
    text-align: center;
    font-weight: 600;
    font-size: 24px;
    margin-bottom: 20px;
  }

  .timeline {
    background: #ffffff;
    box-shadow: 0px 0px 10px 0px #dbdbdb;
    margin-left: 16px;
    padding: 16px 24px;
    overflow: auto;
    .timeline-title {
      align-items: center;
      font-weight: 600;
      padding-bottom: 4px;
    }
  }
}

.change-reason {
  margin-top: 20px;
}

.submit-btn {
  margin-top: 20px;
  text-align: center;
}

.form-item {
  margin-bottom: 15px;
}

.desc-item {
  margin-bottom: 30px;
}

.autonomous-comparison {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 20px;
  background: #fff;
}

.comparison-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.version-box {
  position: relative;
  border-radius: 4px;
  padding: 15px;
}

.old-version {
  background-color: #f8f9fa;
  border-left: 4px solid #909399;
}

.new-version {
  background-color: #f0f9eb;
  border-left: 4px solid #67c23a;
}

.version-label {
  position: absolute;
  top: -12px;
  left: 10px;
  background: white;
  padding: 0 5px;
}

.data-panel {
  margin-top: 10px;
}

/* 响应式适配 */
@media (max-width: 768px) {
  .comparison-container {
    grid-template-columns: 1fr;
  }
}
</style>